// leancloud初始化 param1：应用 id、param2：应用 key
// AV.initialize("w05bibbiykvnuh5k818zui9divdiuy78t30sbuff39daqg2p",
//    "x7pko470mgu5fu32guothturdp4kw7smn3djl2ojpx0h6yfw");
// var TestObject = AV.Object.extend("TestObject");


//用户信息模型
var LedUser = function() {
  //this.userInfo = null;//用户信息

  this.deviceList = [];//设备列表
  this.currentDevice = {};
  this.device_role_map = {};

};

LedUser.prototype = {
  //从URL获取信息
  getParameterByName : function(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  },

  //设置自定义名称
  getAlias : function(alias) {
    $("#pagefive input").val(alias);
  },

  //启用保存按钮
  enableSaveButton : function() {
    $("button.button_save").attr("disabled", false);
    $("#page-display button.display_save").attr("disabled", false);
    $("#page-one .fast_button_save").attr("disabled", false);
  }

}

//设备信息模型
var Submit = function() {
  //当前选取的设备
  this.deviceInfo = null;
  //card参数设置。
  this.cardParams = {
    "manufactor": "kale",
    "card_name": "X4M",
  };
  //display参数设置。
  this.displayParams = {
    "bright_level": 15,
    "entermode": "random_model",
    "delay": 2,
    "speed": 0,
    "text_color": "#ff0000",
    "font": "SimSun",
    "time": "null",
    "time_location": "left",
    };  
  //screen参数设置。
  this.screenParams = {
    //外观
    "width": 0,
    "height": 0,
    "color_num": "",
    //"fast_config": "P10",
    "gray": "1gray",
    //极性
    "data_dir": "normal",
    "str_polar": "high",
    "data_polar": "positive",
    "oe_polar": "high",
    //扫描
    "lineverify": "0lines",
    "frequency": "normal",
    "line_blanking": "line_blanking",
    //屏幕参数
    "screen_type": 1,
    // "scan_mode": 0,
    // "scan_line": 0,
    // "wrap_mode": "",
    // "wrap_bits": "",
    // "screen_split": "false",
    // "data_mirror_alternate": "false",
    // "decode_mode": "",
  };
  //command参数设置
  this.commandParams = {
    "bright_mode": "manual_bright",
    "bright_level": 15,
  };
  //user参数设置
  this.userParams = {
    "protocol_version": "1.0.5",
    "screen_name": "",
    "screen_binding": "bind",
  };
  //常用参数
  this.screen_type = 0;
  this.screen_type_all = {
    "1": "静态扫描,上蛇形,一路数据带4行、8列折行",
    "2": "静态扫描,下蛇形,一路数据带4行、8列折行",
    "3": "静态扫描,上蛇形,一路数据带8行、8列折行",
    "4": "静态扫描,下蛇形,一路数据带8行、8列折行",
    "5": "静态扫描,上蛇形,一路数据带16行、8列折行",
    "6": "静态扫描,下蛇形,一路数据带16行、8列折行",
    "7": "静态扫描,上蛇形,一路数据带8行、16列折行",
    "8": "静态扫描,下蛇形,一路数据带8行、16列折行",
    "9": "静态扫描,上蛇形,一路数据带16行、16列折行",
    "10": "静态扫描,下蛇形,一路数据带16行、16列折行",

    "51": "1/2扫描,直行走线",
    "52": "1/2扫描,上蛇形,一路数据带4行、8列折行",
    "53": "1/2扫描,下蛇形,一路数据带4行、8列折行",
    "54": "1/2扫描,上蛇形,一路数据带8行、8列折行",
    "55": "1/2扫描,下蛇形,一路数据带16行、8列折行",
    "56": "1/2扫描,上蛇形,一路数据带4行、8列折行,无138译码",
    "57": "1/2扫描,下蛇形,一路数据带4行、16列折行,无138译码",

    "101": "1/3扫描,下蛇形,一路数据带8行、16列折行",

    "151": "1/4扫描,上蛇形,一路数据带8行、8列折行",
    "152": "1/4扫描,下蛇形,一路数据带8行、8列折行",
    "153": "1/4扫描,上蛇形,一路数据带8行、8列折行、无138译码",
    "154": "1/4扫描,下蛇形,一路数据带8行、8列折行、无138译码",
    "155": "1/4扫描,上蛇形,一路数据带16行、8列折行",
    "156": "1/4扫描,下蛇形,一路数据带16行、8列折行",
    "157": "1/4扫描,上蛇形,一路数据带16行、8列折行、无138译码",
    "158": "1/4扫描,下蛇形,一路数据带16行、8列折行、无138译码",
    "159": "1/4扫描,上蛇形,一路数据带16行、32列折行",
    "160": "1/4扫描,下蛇形,一路数据带16行、32列折行",
    "161": "1/4扫描,上蛇形,一路数据带16行、32列折行、无138译码",
    "162": "1/4扫描,下蛇形,一路数据带16行、32列折行、无138译码",
    "163": "1/4扫描,上蛇形,一路数据带8行、16列折行",
    "164": "1/4扫描,下蛇形,一路数据带8行、16列折行",
    "165": "1/4扫描,上蛇形,一路数据带8行、16列折行、无138译码",
    "166": "1/4扫描,下蛇形,一路数据带8行、16列折行、无138译码",
    "167": "1/4扫描,直行走线,一路数据带4行",
    // "168": "1/4扫描,上蛇形,一路数据带16行,8列小折行(上蛇形),16列大折行(上蛇形)",
    // "169": "1/4扫描,上蛇形,一路数据带16行,8列小折行(下蛇形),16列大折行(上蛇形)",
    // "170": "1/4扫描,下蛇形,一路数据带16行,8列小折行(上蛇形),16列大折行(下蛇形)",
    // "171": "1/4扫描,下蛇形,一路数据带16行,8列小折行(下蛇形),16列大折行(下蛇形)",
    // "172": "1/4扫描,上蛇形,一路数据带16行,8列小折行(上蛇形),32列大折行(上蛇形)",
    // "173": "1/4扫描,上蛇形,一路数据带16行,8列小折行(下蛇形),32列大折行(上蛇形)",
    // "174": "1/4扫描,下蛇形,一路数据带16行,8列小折行(上蛇形),32列大折行(下蛇形)",
    // "175": "1/4扫描,下蛇形,一路数据带16行,8列小折行(下蛇形),32列大折行(下蛇形)",

    "201": "1/5扫描,下蛇形,一路数据带10行、16列折行、P16、三色",

    "251": "1/6扫描,上蛇形,一路数据带12行、8列折行、强力全彩Q13.33",

    "301": "1/8扫描,上蛇形,一路数据带16行、8列折行",
    "302": "1/8扫描,下蛇形,一路数据带16行、8列折行",
    "303": "1/8扫描,上蛇形,一路数据带16行、16列折行",
    "304": "1/8扫描,下蛇形,一路数据带16行、16列折行",
    "305": "1/8扫描,上蛇形,一路数据带16行、32列折行",
    "306": "1/8扫描,下蛇形,一路数据带16行、32列折行",
    "307": "1/8扫描,上蛇形,一路数据带16行、64列折行",
    "308": "1/8扫描,下蛇形,一路数据带16行、64列折行",

    "351": "1/16扫描,直行走线,一路数据带16行",
    "352": "1/16扫描,直行走线,一路数据带16行、数据反向",
    "353": "1/16扫描,上蛇形,一路数据带16行、8列折、数据镜像",

    //"401": "",
    //"402": "",
  };
};

Submit.prototype = {
  //读取配置信息
  getDeviceConfig : function(myurl, device_id) {
    $.ajax({
      type : 'get',
      url : myurl,
      data : null,
      cache : false,
      dataType : 'json',
      success : function(data) {
        //判断是否是新设备
        alert("data: "+JSON.stringify(data));
        if (data.error || !data.screen_config) {//新设备
          $("div.img_container").hide().next().show();
        } else {
          var sub = new Submit();
          //首先判断参数版本号,并提示升级
          var user_config = data.user_config;
          if (!user_config || user_config.config_version < sub.userParams.config_version) {
            alert("o(*￣▽￣*)ブ，系统升级~请重新设置并保存参数~!");
          }
          //使用取得的配置信息预设页面

          sub.setDeviceConfig(data);

          current_config = data;
          //如果配置为单色则隐藏颜色选项
          if (data.screen_config.color_num == "r") {
            if ($("#page-display")) {
              $("#page-display #text_color").val("#ff0000").selectmenu().selectmenu('refresh');
              $("#page-display #text_color").parent().parent().parent().parent().hide();
            }
          }
          //如果配置为三色则添加颜色选项
          if (data.screen_config.color_num == "rgb") {
            if ($("#page-display")) {
              $("#page-display #text_color").append('<option value="#0000ff">蓝色</option>')
                .append('<option value="#00ffff">青色</option>')
                .append('<option value="#ff00ff">洋红</option>');
            }
          }

          //表单初始化完毕后显示表单
          $("div.img_container").hide().next().show();

          //禁用显示配置页的input
          // if ($("#page-display")) {
          //   //$("#page-display input").attr("disabled", true);
          //   $("#page-display input").attr("style", "display: none");
          // } 

        }
      },
      error : function(data) {
        alert("〒_〒。。。获取配置失败，少侠打开方式不对吧~");

        window.history.back();
        //$("div.img_container").hide().next().show();
      }
    });
  },

  //预设表格每一项
  setFormItems : function(page, params) {
    //遍历设置所有表单项
    for (var item in params) {
      var input_item = $(page + " input#" + item);
      if (input_item.length) {
        //如果是滑块则预设滑块值
        if (item == "bright_level" || item == "delay" || item == "speed") {
          input_item.val(params[item]).slider().slider("refresh");
        } else {
          input_item.val(params[item]);
        }
      };
      var select_item = $(page + " select#" + item);
      if (select_item.length) {
        select_item.val(params[item]).selectmenu().selectmenu('refresh');
        //select_item.selectmenu('refresh');

        //钟表的动态显示
        if (select_item.val() == "dial" || select_item.val() == "digit") {
          select_item.parent().parent().parent().next().show();
        };
      };
      var radio_item = $(page + " input[name=\'"+ item +"\'][type='radio']");
      if (radio_item.length) {
        for (var i = 0; i < radio_item.length; i++) {
          if (radio_item[i].defaultValue == params[item]) {
            radio_item[i].checked = true;
            //radio_item.checkboxradio('refresh');
          } else {
            radio_item[i].checked = false;
          }

          radio_item.checkboxradio().checkboxradio('refresh');
        };
      };
    };
  },

  //使用配置信息预设页面
  setDeviceConfig : function(data) {
    var config = data;
    console.log("current_page: "+JSON.stringify(config));
    // var current_page = document.location.href.match(/easylink.io\/.*.html/)[0];
    var current_page = document.location.href.match(/easylink.io\/.*.html/);
    console.log("current_page: "+current_page);
    //var page_card = "#page-card";
    var page_scr_size = "#page-one";
    var page_scr_polar = "#page-three";
    var page_scr_scan = "#page-four";
    var page_display = "#page-display";

    if (current_page == "easylink.io/display.html") {

      if (config.display_config.speed == 0) {
        config.display_config.speed = MAX_SPEED;
      } else {
        config.display_config.speed = MAX_SPEED - (config.display_config.speed + 1)/100;
      }
      //this.setFormItems(page_card, config.display_config);
      this.setFormItems(page_display, config.display_config);

    } else if (current_page == "easylink.io/index.html") {

      this.setFormItems(page_scr_size, config.screen_config);
      this.setFormItems(page_scr_polar, config.screen_config);
      this.setFormItems(page_scr_scan, config.screen_config);

      //第一页fast_config动态显示单独设置
      if (config.screen_config.screen_type == "401" || config.screen_config.screen_type == "402") {
        $('#fast_frequency').val(config.screen_config.frequency).selectmenu().selectmenu('refresh');
        $('#fast_line_blanking').val(config.screen_config.line_blanking).selectmenu().selectmenu('refresh');
      }

      //第二页屏幕类型单独设置
      screen_type_selected = config.screen_config.screen_type;

      if (screen_type_selected) {
        if (screen_type_selected == "401") {
          $("#page-one #fast_config").val("P10").selectmenu().selectmenu('refresh');
        } else if (screen_type_selected == "402") {
          $("#page-one #fast_config").val("P5").selectmenu().selectmenu('refresh');
        } else {
          $("#page-one #fast_config").val("other").selectmenu().selectmenu('refresh');
          //fast_config动态显示
          $("#page-one #fast_config").parent().parent().parent().parent().next().show().next().hide();
          $("#page-one #page_one_button").hide().next().show();
        }

        var screen_type_name = sub.screen_type_all[screen_type_selected];
        // console.log(screen_type_name);
        // var name_array = screen_type_name.split(",");
        // $("#select_1").val(name_array[0]).selectmenu().selectmenu("refresh");
        // $("#select_2").val(name_array[1]).selectmenu().selectmenu("refresh");
        // if (name_array[2]) {
        //   $("#select_3").val(name_array[2]).selectmenu().selectmenu("refresh");
        // }
        $("#screen_type_name").html("<p>" + screen_type_name +"</p>");

        //$("#dynamic_select").append("<select>")
      }

    }
  },

  //快捷设置信息保存
  fastSaveConfig : function() {
    var config = {
      "screen_config":{},
      "display_config":{},
      "command_config":{},
      "user_config":{},
    };

    var fast_dispaly = sub.displayParams;
    var fast_card = sub.cardParams;
    var fast_screen = sub.screenParams;
    //卡参合并到显参
    $.extend(fast_dispaly, fast_card);//显示参数

    //检查是否有旧的参数
    var old_config = current_config;
    if (old_config.display_config) {
      config.display_config = old_config.display_config;
      config.command_config = old_config.command_config;
    } else {
      config.display_config = fast_dispaly;
      config.command_config = sub.commandParams;
    }

    config.user_config = sub.userParams;
    config.user_config.screen_name = current_device.alias;

    var fast_save = function() {
      fast_screen.width = $('#width').val()? $('#width').val() - 0: $('#width').val();
      fast_screen.height = $('#height').val()? $('#height').val() - 0: $('#height').val();
      fast_screen.frequency = $('#fast_frequency').val();
      fast_screen.line_blanking = $('#fast_line_blanking').val();
      //获取额外屏参并合并到屏参
      $.extend(fast_screen, extr_scr_config);

      config.screen_config = fast_screen;
    };

    switch($("#page-one #fast_config").val()) {
        
      case "P10":
        fast_screen = {
          "width": 0,
          "height": 0,
          "color_num":"r",
          //"fast_config": "P10",

          "data_dir":"normal",
          "str_polar":"high",
          "data_polar":"positive",
          "oe_polar":"high",
          "lineverify":"0lines",
          "frequency":"fastest",
          "line_blanking":"normal",
          "screen_type":"401"
        };
        fast_save();
        break;
        
      case "P5":
        fast_screen = {
          "width": 0,
          "height": 0,
          "color_num":"rg",
          //"fast_config": "P5",

          "data_dir":"normal",
          "str_polar":"high",
          "data_polar":"positive",
          "oe_polar":"high",
          "lineverify":"0lines",
          "frequency":"fastest",
          "line_blanking":"normal",
          "screen_type":"402"
        };
        fast_save();
        break;

      default:
        // no op
    }
    
    return config;
  },

  //保存配置信息
  postDeviceConfig : function(token, deviceId, fromUserName, config) {
    //发送到服务器
    //   var device_id = deviceId.split('/')[1];
      alert(deviceId);
      $.ajax({
        // type : 'post',
        type: 'POST',
        // url : "http://suishou.fr/wechat/device-config?token=" + token +'&deviceId='+ deviceId +'&fromUserName='+ fromUserName,
        url : "http://suishou.fr/wechat/device-config",
        headers : '',
        data : {
          "token": token,
          "deviceId": deviceId,
          "fromUserName": fromUserName,
          "config": JSON.stringify(config)
        },
        cache : false,
        dataType : 'json',
        success : function(data,textState) {
          //console.log("post config success" + JSON.stringify(data));
          alert("(●'◡'●)~保存成功~！"+textState+JSON.stringify(data));
          //启用保存按钮
          var user = new LedUser();
          user.enableSaveButton();
          // $("button.button_save").attr("disabled", false);
          // $("#page-display button.display_save").attr("disabled", false);

          //localStorage.setItem(deviceId, JSON.stringify(config));
          //保存成功后打开提示页面
          //window.open('#pagethree', '_self');
          //$.mobile.changePage("#pagethree",{transition: "fade", changeHash: false });
        },
        error : function(data) {
          alert("〒_〒。。。保存参数失败~戳我再试一次" + data.responseText);
          //启用保存按钮
          var user = new LedUser();
          user.enableSaveButton();
          // $("button.button_save").attr("disabled", false);
          // $("#page-display button.display_save").attr("disabled", false);
        }
      });
  },

  //从URL获取信息
  getParameterByName : function(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
  },

  //将表单display数据保存到JSON对象。
  saveDisplayParams : function(params) {
    var displayParams = params;

    //获取可由id获取的显示参数
    var input_form = $('#page-display form input');
    for (var i = 0; i < input_form.length; i++) {
      var key = input_form[i].id;
      if (key == "speed") {
        if (input_form[i].value == MAX_SPEED) {
          var value = 0;
        } else {
          var value = (MAX_SPEED - input_form[i].value)*100 - 1;
        }
      } else {
        var value = input_form[i].value;
      }
      displayParams[key] = value - 0;
    }
    var select_form = $('#page-display form select');
    for (var i = 0; i < select_form.length; i++) {
      var key = select_form[i].id;
      var value = select_form[i].value;
      displayParams[key] = value;
    }

    return displayParams;
  },

  //将表单card数据保存到JSON对象。
  saveCardParams : function(params) {
    var cardParams = params;
    cardParams.manufactor = $('#page-card select#manufactor').val();
    cardParams.card_name = $('input[name="card_name"]:checked').val();

    //有不同厂商时动态加载卡参数
    // var card_selector = "#card_list #" + cardParams.card_name + " select";
    // var $card_form = $(card_selector);
    // //alert($card_form.length);
    // for (var i = 0; i < $card_form.length; i++) {
    //   var key = $card_form[i].id;
    //   var value = $card_form[i].value;
    //   cardParams[key] = value;
    // }
    //alert(JSON.stringify(cardParams));
    return cardParams;
  },

  //将表单screen数据保存到JSON对象。
  saveScreenParams : function(params) {
    var screenParams = params;
    //外观
    screenParams.width = $('#width').val()? $('#width').val() - 0: $('#width').val();
    screenParams.height = $('#height').val()? $('#height').val() - 0: $('#height').val();
    screenParams.color_num = $('[name="color_num"]:checked').val();
    //screenParams.gray = $('[name="gray"]:checked').val();
    //扫描
    screenParams.lineverify = $('#lineverify').val();
    screenParams.frequency = $('#frequency').val();
    screenParams.line_blanking = $('#line_blanking').val();
    //极性
    screenParams.data_dir = $('[name="data_dir"]:checked').val();
    screenParams.str_polar = $('[name="str_polar"]:checked').val();
    screenParams.data_polar = $('[name="data_polar"]:checked').val();
    screenParams.oe_polar = $('[name="oe_polar"]:checked').val();
    //屏幕参数
    screenParams.screen_type = screen_type_selected;
    // screenParams.scan_mode = $('#scan_mode').val();
    // screenParams.scan_line = $('#scan_line').val()? $('#scan_line').val() - 0: $('#scan_line').val();
    // screenParams.wrap_mode = $('[name="wrap_mode"]:checked').val();
    // screenParams.wrap_bits = $('[name="wrap_bits"]:checked').val();
    // screenParams.decode_mode = $('#decode_mode').val();

    return screenParams;
  },

  //将command数据保存到JSON对象。
  saveCommandParams : function(params) {
    var commandParams = params;
    if ($("#page-display")) {
      commandParams.bright_level = $("#page-display #bright_level").val();
    }

    return commandParams;
  },

  //循环检查屏幕参数
  checkForm : function(params) {
    var result = true;
    if (params.height === "" || params.width === "") {
      alert("(￣▽￣)\"~木有填写屏幕尺寸哦骚年~");
      result = false;
    }
    return result;
  },

  //动态加载下拉菜单
  appendSelect : function(index, list) {
    var index_parent = index -1;
    var select_parent = $('select#select_'+ index_parent).val();
    var select_child = "";

    //清空过滤参数
    var screen_type_filtered = {};

    var $select_child = $('<select id="select_'+ index +'"></select>');
    for(var item in list) {
      var name_array = list[item].split(",");
      if (name_array[index - 2] === select_parent) {
        screen_type_filtered[item] = list[item];

        if (name_array[index - 1] && select_child.indexOf(name_array[index - 1]) < 0) {
          $select_child.append("<option value='"+ name_array[index - 1] +"'>"+ name_array[index - 1] +"</option>");
          select_child += name_array[index - 1];
        }
      }
    }

    //删除原有的select_2
    if ($("select#select_"+ index).length) {
      $("#dynamic_select select").not($("#select_"+ index_parent)).not($("#select_"+ (index_parent-1))).remove();
    }
    //挂载新的select_2
    if ($select_child.children().length > 0) {
      $select_child.appendTo($("#dynamic_select")).selectmenu();
    }

    return screen_type_filtered;
  },

  //动态设置文本框结果
  setTextarea : function(list) {
    var name = $('select#select_3').val();

    for(var item in list) {
      var name_array = list[item].split(",");
      if (name_array[2] == name) {
        screen_type_selected = item;

        sub.fetchTypeConfig(item);
        $("button.button_save").attr("disabled", true);

        $("#screen_type_name").empty().append('<p>'+ list[item] +'</p>');
      }
    }
  },

  //获取screen_type额外参数
  fetchTypeConfig : function(item) {

    $.ajax({
      type : 'get',
      url : 'http://suishou.fr/wechat/common-config',
      headers : '',
      data : {
        'screen_type' : item
      },
      cache : false,
      dataType : 'json',
      success : function(result) {
        alert("success" + JSON.stringify(result));

        extr_scr_config = result;
        user.enableSaveButton();

      },
      error : function(data) {
        console.log("失败了" + data.responseText);
        alert("〒_〒。。获取详细参数失败~连上wifi了吗骚年？");
        window.history.back();
      }
    });
  },

  //获取用户列表
  fetchUsers : function(access_token, device_id) {
    //访问easylink获取微信sdk的key
    // $.ajax({
    //   type : 'get',
    //   url : 'http://e5d5ea6a-952b-4e7e-b3ae-e80cef18e0f3.app.easylink.io/sign.php',
    //   headers : {
    //     'Authorization' : 'token '+ access_token
    //   },
    //   // data : {
    //   //   'app_id' : APP_ID,
    //   //   'device_id' : device_id
    //   // },
    //   cache : false,
    //   dataType : 'json',
    //   success : function(data) {
    //     console.log("success" + data);

    //     wx.config({
    //       debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    //       appId: data.appId, // 必填，公众号的唯一标识
    //       timestamp: data.timestamp, // 必填，生成签名的时间戳
    //       nonceStr: data.nonceStr, // 必填，生成签名的随机串
    //       signature: data.signature,// 必填，签名，见附录1
    //       jsApiList: [] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    //     });

    //   },
    //   error : function(data) {
    //     console.log("失败了" + data.responseText);
    //     //alert("获取用户列表失败！");
    //     //window.history.back();
    //   }
    // });
    // return;


    $.ajax({
      type : 'post',
      url : 'http://api.easylink.io/v1/device/user/query',
      headers : {
        'Authorization' : 'token '+ access_token,
        'X-Application-Id' : APP_ID,
      },
      data : {
        'app_id' : APP_ID,
        'device_id' : device_id
      },
      cache : false,
      dataType : 'json',
      success : function(data) {
        console.log("success" + data);

        $.ajax({
          type : 'post',
          url : 'http://api.easylink.io/v1/wechat/accessToken/get',
          headers : {
            'Authorization' : 'token '+ access_token,
            'X-Application-Id' : APP_ID,
          },
          data : {
            'app_id' : APP_ID
          },
          cache : false,
          dataType : 'json',
          success : function(result) {
            console.log("success" + result.access_token);

            var wechat_token = result.access_token;
            //取出用户列表每一项
            for (var i = 0; i < data.length; i++) {

              sub.fetchWechatUserInfo(wechat_token, data[i]);

            };

            //隐藏进度条
            $("div.img_container").hide().next().show();
          },
          error : function(data) {
            console.log("失败了" + data.responseText);
            alert("〒_〒。。获取token失败~连上wifi了吗骚年？");
            window.history.back();
          }
        });


        //$("#page0 li h2").eq(current_device.current_index).html(my_alias);
        //alert("成功获取easylink.io用户列表！");
        //打开页面时显示进度条
        //$("div.img_container").hide().next().show();

      },
      error : function(data) {
        console.log("失败了" + data.responseText);
        alert("〒_〒。。获取用户列表失败~连上wifi了吗骚年？");
        window.history.back();
      }
    });
  },
  //通过用户id获取用户基本信息
  fetchWechatUserInfo : function(wechat_token, info) {

    var rawUrl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='+ wechat_token +'&openid=' + info.username;
    var base64 = BASE64.encoder(rawUrl);

    $.ajax({
      type : 'get',
      url : 'http://suishou.fr/wechat/jsonp?callback=my_wechat_cb',
      data : {
        'url' : base64,
      },
      cache : false,
      dataType : 'jsonp',
      callback : 'my_wechat_cb',
      success : function(data) {
        var unicode = BASE64.decoder(data);
        var user_info = '';  
        for(var i = 0 , len =  unicode.length ; i < len ;++i){  
              user_info += String.fromCharCode(unicode[i]);  
        }
        user_info = JSON.parse(user_info);
        console.log("success" + user_info.nickname);

        if (!user_info.nickname) {return;}

        var user_id = info.username;
        var user_name = user_info.nickname;
        var user_role = info.role;

        var role_map = {"owner": "管理员", "share": "普通用户"};
        var role_name = role_map[user_role];

        if (user_role == "owner") {

          $("#user-list").prepend('<li style="margin-bottom: .8em" class="ui-li-has-thumb"><a href="#'
            + user_id +'/'+ user_name + '" data-rel="popup" data-position-to="window" class="ui-btn ui-corner-all"><img src="../image/user_'
            + user_role + '.png"><h2>'
            + user_name + '</h2><p>'
            + role_name + '</p></a></li>'
            );
          // var $popup = $('<div id="'+ user_id +'/'+ user_name +'" data-role="popup" data-overlay-theme="a" class="ui-content"></div>').append($("#pagesix ul.authorize-pop").clone());
          // $popup.appendTo($("#user-list li:first-child")).popup();

        } else {

          $("#user-list").append('<li style="margin-bottom: .8em" class="ui-li-has-thumb"><a href="#'
            + user_id +'/'+ user_name + '" data-rel="popup" data-position-to="window" class="ui-btn ui-corner-all"><img src="../image/user_'
            + user_role + '.png"><h2>'
            + user_name + '</h2><p>'
            + role_name + '</p></a></li>'
            );
          var $popup = $('<div id="'+ user_id +'/'+ user_name +'" data-role="popup" data-overlay-theme="a" class="ui-content"></div>').append($("#pagesix ul.authorize-pop").clone());
          $popup.appendTo($("#user-list li:last-child")).popup();

        }

      },
      error : function(data) {
        console.log("失败了" + data.responseText);
        alert("〒_〒。。获取用户昵称失败~");
        window.history.back();
      }
    });

  }
};




//格式化日期，来源于网络
// 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.Format = function(fmt) { //author: meizz   
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}  